



use serde_json::{Value, Number};
use crate::source::SourceResult;
use crate::conf_init::ResultErr;
use crate::data_frame::{DataFrame, ElementValue, RealValue};
use crate::run_plan::{HandResult, HandResultOk};
use std::str::FromStr;
use std::sync::Arc;

pub struct JsonValue{
    json: Value,
}

impl JsonValue{
    pub fn new(json: &str)->Result<Arc<JsonValue>,ResultErr>{
        //let json = Value::from_str(json)?;
        //return Ok(Box::new(JsonValue{json: json}));
        return Result::Err(ResultErr::new(format!("aaa")));
    }
}

impl DataFrame for JsonValue{
    fn get_value(&self, key: &ElementValue)->HandResult{
        let mut value = &self.json;

        for k in key.element.iter(){
            match value{
                Value::Object(t) => {
                    if let Some(t) = t.get(k){
                        value = t;
                    }else{
                        return HandResult::Ok(HandResultOk::new(RealValue::Null));
                    }
                },
                _ => {return HandResult::Ok(HandResultOk::new(RealValue::Null));},
            }
        }

        if key.element.len() > 0{
            match value{
                Value::String(v) => {
                    return HandResult::Ok(HandResultOk::new(RealValue::Utf8(v.to_string())));
                },
                Value::Bool(v) => {
                    return HandResult::Ok(HandResultOk::new(RealValue::Boolean(v.clone())));
                },
                Value::Number(v) => {
                    let vvv = if let Some(vv) = v.as_u64(){
                        RealValue::U64(vv)
                    } else if let Some(vv) = v.as_i64(){
                        RealValue::I64(vv)
                    } else if let Some(vv) = v.as_f64(){
                        RealValue::F64(vv)
                    }else{
                        return HandResult::Ok(HandResultOk::new(RealValue::Null));
                    };
                    return HandResult::Ok(HandResultOk::new(vvv));
                },
                Value::Null => {
                    return HandResult::Ok(HandResultOk::new(RealValue::Null));
                },
                Value::Array(v) => {
                    return HandResult::Ok(HandResultOk::new(RealValue::Null));
                },
                Value::Object(v) => {
                    return HandResult::Ok(HandResultOk::new(RealValue::Null));
                },
            }
        }else{
            return HandResult::Ok(HandResultOk::new(RealValue::Null));
        }
    }
}